import { Injectable } from '@angular/core';
import {
  CanActivate,
  CanActivateChild,
  CanLoad,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  Router,
  Route
} from '@angular/router';
import { LocalStorage } from './localstorage';
import { NzModalService } from 'ng-zorro-antd/modal';

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {

  constructor(
    private router: Router,
    private modalService: NzModalService
  ) {
  }

  // 路由守卫
  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    // 登录校验
    if (!this.checkLogin()) {
      return false;
    }

    // 菜单权限的校验
    return this.checkMenu(state.url);
  }

  canActivateChild(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    // 登录校验
    if (!this.checkLogin()) {
      return false;
    }

    // 菜单权限的校验
    return this.checkMenu(state.url);
  }

  canLoad(route: Route) {
    return true;
  }

  checkLogin(): boolean {
    let isLogin: boolean = LocalStorage.isToken();

    // 为真表示已登录
    if (!isLogin) {
      this.modalService.warning({
        nzTitle: '警告',
        nzContent: '登录已失效，请重新登录。',
        nzOnOk: () => {
          this.router.navigate(['/', 'login']);
        }
      });
      return false;
    }

    return true;
  }

  // 菜单权限的校验
  checkMenu(url) {
    if (url == '/wel' || url == '/wel/' || url == '/wel/home' || url == '/wel/home/') {
      return true;
    }

    url = url.replace('/wel/', '');
    let menus = JSON.parse(LocalStorage.getMenus());
    if (this.menuCheck(menus, url)) {
      return true;
    } else {
      // 权限不存在时，打开默认页即首页
      this.router.navigateByUrl('/wel');
    }
  }

  // 校验url在menu中是否存在
  menuCheck(menus, url) {
    if (menus.length == 0) {
      return false;
    }

    // 校验父菜单
    for (let i in menus) {
      let menu = menus[i];
      if (menu['path'] == url) {
        return true;
      }

      // 校验子菜单
      if (menu['children'] && menu['children'].length > 0) {
        let rtn = this.menuCheck(menu['children'], url);
        if (rtn) {
          return true;
        }
      }
    }

    return false;
  }
}

